package com.ahmedmisbah.andgenplus.utils.velocity;

import java.io.StringWriter;
import java.util.Iterator;
import java.util.Properties;
import java.util.Set;

import org.apache.velocity.VelocityContext;
import org.apache.velocity.app.Velocity;

import com.ahmedmisbah.andgenplus.constants.GlobalConstants;

/**
 * Utility class for handling all Velocity Template related operations
 * 
 * @author Ahmed Mahmoud Misbah
 */
public class VelocityUtil {

	/**
	 * Build a velocity template given its parameters and returns a string
	 * representation of the constructed template
	 * 
	 * @param templateName
	 *            full path of template
	 * @param properties
	 *            template properties to be mapped
	 * @return String representation of template after being constructed
	 * @throws Exception
	 */
	public static String buildTemplate(VelocityTemplate template)
			throws Exception {

		String ret = null;

		Properties p = new Properties();
		p.setProperty("resource.loader", "class");
		p.setProperty("class.resource.loader.class",
				"org.apache.velocity.runtime.resource.loader.ClasspathResourceLoader");
		Velocity.init(p);

		StringWriter writer = new StringWriter();

		VelocityContext context = new VelocityContext();

		Set<String> keys = template.getProperties().keySet();
		Iterator keyIterator = keys.iterator();

		while (keyIterator.hasNext()) {
			String propertyName = (String) keyIterator.next();
			Object propertyValue = template.getProperties().get(propertyName);
			context.put(propertyName, propertyValue);
		}

		String defaultEncoding = GlobalConstants.DEFAULT_ENCODING;

		Velocity.mergeTemplate(template.getTemplatePath(), defaultEncoding, context, writer);
		ret = writer.toString();

		return ret;

	}
}
